﻿using MediatR;
using Schedulingclasses.Api.User.Command;
using Schedulingclasses.Domain;
using Schedulingclasses.ErrorCode;
using Schedulingclasses.Infrastructure;

namespace Schedulingclasses.Api.User.Handler
{
    public class SraechInstancceHandler : IRequestHandler<SraechInstancceCommand, ApiPaging<instancce>>
    {
        private readonly ILogger<SraechInstancceHandler> logger;
        private readonly IBaseRepository<instancce> instancce;

        public SraechInstancceHandler(ILogger<SraechInstancceHandler> logger,IBaseRepository<instancce> instancce)
        {
            this.logger = logger;
            this.instancce = instancce;
        }

        public async Task<ApiPaging<instancce>> Handle(SraechInstancceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("查找成功");
                var res=new ApiPaging<instancce>();


                //根据角色查看对应数据
                var instancces = instancce.Getlist().Where(x=>x.StatusId.Equals(1)&&x.UserId.Equals(request.UserId));

                //管理员查看所有数据
                if (request.UserId == 2)//2表示管理员
                {
                    instancces=instancce.Getlist();
                }

                res.TotalCount= instancces.Count();
                res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / request.PageSize);
                res.PageData= instancces.OrderByDescending(x=>x.instancceId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();

                res.msg = "查找成功";
                res.code = ApiREunm.OK;
                return res;

            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }
    }
}
